package impl

import (
	"context"

	"gitee.com/zatto/project/tree/master/vblog/api/apps/blog"
	"gitee.com/zatto/project/tree/master/vblog/api/apps/tag"
)

func (i *impl) CreateTag(ctx context.Context, req *tag.CreateTagRequest) (*tag.Tag, error) {
	ins, err := tag.NewTag(req)
	if err != nil {
		return nil, err
	}

	// 查询文章是否存在
	_, err = i.blog.DescribeBlog(ctx, blog.NewDescribeBlogRequest(req.BlogId))
	if err != nil {
		return nil, err
	}

	// 对象入库
	if err := i.db.WithContext(ctx).Create(ins).Error; err != nil {
		return nil, err
	}

	return ins, nil
}

func (i *impl) QueryTag(ctx context.Context, req *tag.QueryTagRequest) (*tag.TagSet, error) {
	query := i.db.Table("tags").WithContext(ctx)
	if len(req.BlogIds) > 0 {
		query = query.Where("blog_id IN (?)", req.BlogIds)
	}
	set := tag.NewTagSet()
	err := query.Order("created_at DESC").Find(&set.Items).Error
	if err != nil {
		return nil, err
	}
	set.Total = int64(len(set.Items))
	return set, nil
}

func (i *impl) RemoveTag(ctx context.Context, req *tag.RemoveTagRequest) (*tag.TagSet, error) {
	qReq := tag.NewQueryTagRequest()
	qReq.Add(req.BlogId)
	set, err := i.QueryTag(ctx, qReq)
	if err != nil {
		return nil, err
	}

	if set.Total == 0 {
		return set, nil
	}

	err = i.db.Table("tags").WithContext(ctx).Where("blog_id = ?", req.BlogId).Delete(&tag.Tag{}).Error
	if err != nil {
		return nil, err
	}

	return set, nil
}
